<?php
namespace app\common\service;

use think\Model;

class ClassCommitteeLevelService extends BaseService
{


    /**
     * 后台: 获取班委头衔列表
     * @param $sid
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getClassCommitteeLevelList($sid){
        $list = db('class_committee_level')->field('id,name,sorting')->where(['sid' => $sid, 'status' => 1])->order('sorting ASC')->select();
        return $list;
    }


    /**
     * 后台: 新增或更新班委头衔
     * @param $sid
     * @param int $id
     * @param $name
     * @param $sorting
     * @return array
     * @throws \think\Exception
     */
    public function saveClassCommitteeLevel($sid, $id = 0, $name, $sorting){
        if($id > 0){
            $info = db('class_committee_level')->where(['sid' => $sid, 'name' => $name, 'status' => 1, 'id' => ['<>', $id]])->find();
            if($info){
                return ['status' => 0, 'msg' => '已存在相同名称'];
            }
            //更新
            $r = db('class_committee_level')->where(['id' => $id])->update(['name' => $name, 'sorting' => $sorting, 'edit_time' => time()]);
        } else {
            $info = db('class_committee_level')->where(['sid' => $sid, 'name' => $name, 'status' => 1])->find();
            if($info){
                return ['status' => 0, 'msg' => '已存在相同名称'];
            }
            //新增
            $data = [
                'name' => $name,
                'sid' => $sid,
                'sorting' => $sorting,
                'add_time' => time()
            ];
            $r = db('class_committee_level')->insert($data);
        }

        return $r ? ['status' => 1, 'msg' => '保存成功'] : ['status' => 0, 'msg' => '保存失败'];
    }


    /**
     * 后台: 删除班委头衔
     * @param $sid
     * @param $id
     * @return int|string
     * @throws \think\Exception
     */
    public function deleteClassCommitteeLevel($sid, $id){
        //查询是否引用了教务头衔
        $info = db('class_students')->where(['sid' => $sid, 'class_committee_level_id' => $id])->find();
        if($info){
            return ['status' => 0, 'msg' => '该头衔正在被引用，无法删除'];
        }

        $r = db('class_committee_level')->where(['sid' => $sid, 'id' => $id])->update(['status' => -1, 'edit_time' => time()]);
        return $r ? ['status' => 1, 'msg' => '删除成功'] : ['status' => 0, 'msg' => '删除失败'];
    }

}







